package hhm.framessm.authority.service.impl;

import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.pool.DruidDataSource;

import hhm.framessm.authority.service.RoleService;
import hhm.framessm.pojo.TbPermission;
import hhm.framessm.pojo.TbRole;

@Service
public class RoleServiceImpl implements RoleService {
	@Autowired
	private DruidDataSource dataSource;

	@Override
	public void insertRole(TbRole role) {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateRole(TbRole role) {
		// TODO Auto-generated method stub

	}

	@Override
	public void deleteRole(String id) {
		// TODO Auto-generated method stub

	}

	@Override
	public TbRole findRoleById(Integer id) {
		QueryRunner runner = new QueryRunner(dataSource);
		String sql = "select role_id,role_name,description from tb_role where role_id=?";
		Object[] params = { id };
		try {
			TbRole role = (TbRole) runner.query(sql, new BeanHandler(TbRole.class), params);
			sql = "select p.id,p.name,p.description from tb_permission p,tb_permission_role pr where p.id=pr.permission_id and pr.role_id=?";
			params = new Object[] { id };
			Set<TbPermission> set = new HashSet<TbPermission>();
			set.addAll((List<TbPermission>) runner.query(sql, new BeanListHandler(TbPermission.class), params));
			role.setTbPermissions(set);
			return role;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	@Override
	public List<TbRole> fineAllRole() {
		List<TbRole> list = null;
		QueryRunner runner = new QueryRunner(dataSource);
		String sql = "select role_id as 'roleId',role_name as 'roleName',description from tb_role";
		try {
			list = (List<TbRole>) runner.query(sql, new BeanListHandler(TbRole.class));
			sql = "select p.id,p.name,p.description from tb_permission p,tb_permission_role pr where p.id=pr.permission_id and pr.role_id=?";
			for (TbRole role : list) {
				Object[] params = new Object[] { role.getRoleId() };
				Set<TbPermission> set = new HashSet<TbPermission>();
				set.addAll((List<TbPermission>) runner.query(sql, new BeanListHandler(TbPermission.class), params));
				role.setTbPermissions(set);
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		return list;
	}

}
